package com.chen.kafla.log.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.kafla.log.entity.MessageEntity;
import com.chen.kafla.log.service.MessageService;
import com.chen.kafla.log.util.JsonResult;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController
@RequestMapping("/data")
@Log4j2
public class DataController {


    @Autowired
    private MessageService service;


    /**
     * 获取所有的数据
     *
     * @return
     */
    @RequestMapping("/getLogAll")
    public JsonResult getLogAll(Page page, @RequestParam Map<String, Object> params) {

        String search = MapUtils.getString(params, "search");
        String startTime = MapUtils.getString(params, "startTime");
        String endTime = MapUtils.getString(params, "endTime");
        Integer code = MapUtils.getInteger(params, "code");

        QueryWrapper<MessageEntity> wrapper = new QueryWrapper();

        wrapper.eq(code != null, "error_code", code);
        wrapper.and(StringUtils.isNotBlank(search), ts -> ts.like("error_title", search)
                .or()
                .like("server_name", search)
                .or()
                .like("error_message", search));
        wrapper.between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), "create_time", startTime, endTime);
        wrapper.orderByDesc("create_time");
        IPage dataList = service.page(page, wrapper);
        return JsonResult.success(dataList);
    }


    @RequestMapping("/getDetail")
    public JsonResult getDetail(Long id) {
        if (id == null) {
            return JsonResult.errorForEmpty();
        }
        return JsonResult.success(service.getById(id));
    }


}
